﻿using HyEduOnline.Data;
using HyEduOnline.Entities;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HyEduOnline.Server.Student;
using HyEduOnline.Server.Teacher;
using HyEduOnline.Server.Admin;
using System.Collections;
using HyEudOnline.Server.Common;

namespace WebSite.Areas.WebApi.Controllers
{
    //考试安排相关操作
    public class ExamController : BaseController
    {

        private StudentsDAO studentsDAO = new StudentsDAO();
        private TestLibPaperDAO testLibPaperDAO = new TestLibPaperDAO();
        private TestStudentsDAO testStudentsDAO = new TestStudentsDAO();
        private TestPaperStrategyDAO testPaperStrategyDAO = new TestPaperStrategyDAO();
        private TestLibDAO testLibDAO = new TestLibDAO();
        private TestLibOptionDAO testLibOptionDAO = new TestLibOptionDAO();
        private TestStuAnswerOptionsDAO testStuAnswerOptionsDAO = new TestStuAnswerOptionsDAO();
        private TestLibPaperDetailDAO testLibPaperDetailDAO = new TestLibPaperDetailDAO();
        private TestStuAnswerDetailDAO testStuAnswerDetailDAO = new TestStuAnswerDetailDAO();
        private TestStuAnswerDAO testStuAnswerDAO = new TestStuAnswerDAO();
        

        /// <summary>
        /// 更新数据
        /// </summary>
        /// <param name="id">试卷id</param>
        /// <param name="paperItem"></param>
        /// <param name="stuIds"></param>
        /// <returns></returns>
        public int Put(int id, TbTestLibPaper paperItem, string stuIds)
        {


            if (id != paperItem.Id)
            {
                //数据无效
                return -1;
            }
            try
            {
                testLibPaperDAO.Update(paperItem);//更新试卷表
                //学生考试表中字段
                TList<TbTestStudents> testStuList = testStudentsDAO.GetByPage("I_PaperID=" + paperItem.Id, 0, int.MaxValue);
                //学生考试表存在这些字段
                if (testStuList.Count != 0)
                {
                    foreach (var item in testStuList)
                    {
                        //更新学生考试表的字段
                        item.DTestTime = paperItem.DTestTime;
                        testStudentsDAO.Update(item);
                    }
                }
                //选择了学生
                if (!string.IsNullOrEmpty(stuIds))
                {

                    string[] stuIdAndCode = stuIds.Split(new char[] { ',' });
                    List<int> paperIdList = new List<int>();
                    foreach (var item in stuIdAndCode)
                    {
                        //ID与code分开
                        string[] stuInfor = item.Split(new char[] { ':' });
                        int stuId = int.Parse(stuInfor[0]);
                        //若已安排该学生，则不重复添加
                        IList<TbTestStudents> stuList = testStudentsDAO.findByIStuId(stuId);
                        if (stuList.Count > 0)
                        {
                            foreach (var stuItem in stuList)
                            {
                                paperIdList.Add((int)stuItem.IPaperId);//取出当前学生所有考试
                            }
                            if (paperIdList.Contains(id))//若当期学生有此考试记录，则不重复添加
                            {
                                continue;
                            }
                        }
                        TbTestStudents testStudent = new TbTestStudents();
                        //考试学生添加到表中
                        ClassValueCopier.Copy(testStudent, paperItem);
                        
                        testStudent.IPaperId = id;
                        testStudent.IStuId = stuId;
                        testStudent.SStuCode = stuInfor[1];
                        testStudent.SClassName = studentsDAO.GetByID((int)testStudent.IStuId).SClassName;
                        testStudent.ICompleted = 0;
                        testStudentsDAO.Insert(testStudent);
                    }
                }
            }
            catch (Exception ex)
            {
                //更新数据失败
                return -2;
            }
            //更新成功
            return 1;
        }




        /// <summary>
        /// 删除考试,参加此考试的学生,组卷策略一并删除
        /// </summary>
        /// <param name="ids">试卷ID eg："1，2，3"</param>
        /// <returns></returns>
        public int DeleteIds(string ids)
        {
            try
            {
                testLibPaperDAO.Del(ids);
                string[] paperIds = ids.Split(new char[] { ',' });
                foreach (var item in paperIds)
                {
                    TList<TbTestStudents> tempStuList = testStudentsDAO.GetByPage("I_PaperId=" + item, 0, int.MaxValue);
                    testStudentsDAO.Del(tempStuList);
                    TList<TbTestPaperStrategy> tempStraList = testPaperStrategyDAO.GetByPage("I_PaperID=" + item, 0, int.MaxValue);
                    testPaperStrategyDAO.Del(tempStraList);
                }
            }
            catch (Exception ex)
            {
                //批量删除是出错
                return -2;
            }
            //批量删除成功
            return 1;
        }


        /// <summary>
        /// 考试安排，获取有资格考试的班级，以JSON类型返回
        /// </summary>
        /// <param name="TeaCode">教师工号</param>
        /// <param name="CourseId">课程ID</param>
        /// <param name="TermId">学年学期ID</param>
        /// <returns></returns>
        public JsonResult GetClass(string TeaCode, int CourseId, int TermId = 1)
        {
            //调用存储过程得到数据集
            DataSet classDSTemp = DataRepository.Provider.TbDeanStuSelCourseProvider.selClass(TeaCode, CourseId, TermId);
            DataTable classDTTemp = classDSTemp.Tables[0];
            List<TbDeanStuSelCourse> classList = new List<TbDeanStuSelCourse>();
            //循环表的每一行
            foreach (DataRow item in classDTTemp.Rows)
            {
                TbDeanStuSelCourse stuClass = new TbDeanStuSelCourse();
                stuClass.IClassId = int.Parse(item[0].ToString());
                stuClass.SClassCode = item[1].ToString();
                stuClass.SClassName = item[2].ToString();
                classList.Add(stuClass);
            }
            return Json(classList);
        }

        /// <summary>
        /// 获取班级，以list的类型返回
        /// </summary>
        /// <param name="TeaCode"></param>
        /// <param name="CourseId"></param>
        /// <param name="TermId"></param>
        /// <returns></returns>
        public List<TbDeanStuSelCourse> GetClassList(string TeaCode, int CourseId, int TermId = 1)
        {
            //调用存储过程得到数据集
            DataSet classDSTemp = DataRepository.Provider.TbDeanStuSelCourseProvider.selClass(TeaCode, CourseId, TermId);
            DataTable classDTTemp = classDSTemp.Tables[0];
            List<TbDeanStuSelCourse> classList = new List<TbDeanStuSelCourse>();
            //循环表的每一行
            foreach (DataRow item in classDTTemp.Rows)
            {
                TbDeanStuSelCourse stuClass = new TbDeanStuSelCourse();
                stuClass.IClassId = int.Parse(item[0].ToString());
                stuClass.SClassCode = item[1].ToString();
                stuClass.SClassName = item[2].ToString();
                classList.Add(stuClass);
            }
            return classList;
        }



        /// <summary>
        /// 获取考试班级所有学生
        /// </summary>
        /// <param name="classStr">班级编号</param>
        /// <returns></returns>
        public JsonResult GetStudent(string classStr)
        {
            string[] classList = classStr.Split(new char[] { ',' });
            List<TbStudents> stuList = new List<TbStudents>();
            foreach (var item in classList)
            {
                List<TbStudents> temp = studentsDAO.findBySClassCode(item).ToList();
                stuList.AddRange(temp);
            }
            return Json(stuList);
        }

        /// <summary>
        /// 获取题目
        /// </summary>
        /// <param name="LibId"></param>
        /// <returns></returns>
        public JsonResult SearchTopic(int LibId,int PaperId = 0)
        {
            int stuId = frontCurrentStu.GetUserID();
            int count = 0;
            string answer = "";//学生选择的答案
            string whereClause = "I_StuID=" + stuId + "  and I_LibID=" + LibId + " and I_PaperID=" + PaperId;
            //获取学生选择的答案
            TList<TbTestStuAnswerOptions> selOptionList = testStuAnswerOptionsDAO.GetByPage(whereClause, 0, int.MaxValue, "DSelTime", "DESC", out count);
            if (selOptionList.Count != 0)
            {
                foreach (var item in selOptionList)
                {
                    answer = answer + ":" + item.IOptionId;
                }
            }
            //获取题目信息
            TbTestLib tempLib = testLibDAO.GetByID(LibId);
            IList<TbTestLibOption> optionList = testLibOptionDAO.findByILibId(LibId);
            return Json(new { lib = tempLib, options = optionList, answer = answer });
        }

        /// <summary>
        /// 提交当前题目答案，同时获取下一题
        /// </summary>
        /// <param name="NextLibId"></param>
        /// <param name="Answer"></param>
        /// <returns></returns>
        public JsonResult NextTopic(int NextLibId, string Answer, int PaperId, int DetailId = 0, int LibId = 0, int StrategyId = 0)
        {
            int id = frontCurrentStu.GetUserID();//当前学生的ID
            string code = frontCurrentStu.GetNo();
            if (!string.IsNullOrEmpty(Answer))//选择了答案
            {
                int isTrue = 1;//该题是否做对                
                string[] answerList = Answer.Split(new char[] { ',' });
                int answerLenght = answerList.Length ;//学生选择的答案个数；
                TList<TbTestStuAnswerOptions> tempOptionList = testStuAnswerOptionsDAO.GetByPage(
                    "I_LibID=" + LibId + " and I_StuID=" + id, 0, int.MaxValue);
                //修改答案，则删除以前的记录，再重新插入
                if (tempOptionList.Count != 0)
                {
                    testStuAnswerOptionsDAO.Del(tempOptionList);
                    TList<TbTestStuAnswerDetail> tempDetailList = testStuAnswerDetailDAO.GetByPage(
                        "I_PaperDetailID=" + DetailId + " and I_StuID=" + id, 0, int.MaxValue);
                    testStuAnswerDetailDAO.Del(tempDetailList);
                }
                //在testStuAnswerOptions（答案选项表）插入数据
                foreach (var item in answerList)
                {
                    int optionId = int.Parse(item);
                    TbTestLibOption option = testLibOptionDAO.GetByID(optionId);//当前选项
                    int isOk = (int)option.IIsTrue;//当前选项是否正确
                    TbTestStuAnswerOptions tempOption = new TbTestStuAnswerOptions();
                    tempOption.IStuId = id;
                    tempOption.SStuCode = code;
                    tempOption.IOptionId = optionId;
                    tempOption.DSelTime = DateTime.Now;
                    tempOption.ILibId = LibId;
                    tempOption.IIsOk = isOk;
                    tempOption.IPaperId = PaperId;
                    //少选多选一个，为错
                    int libId = (int)option.ILibId;
                    //正确答案长度
                    int selLength = testLibOptionDAO.GetByPage(
                        "I_LibID=" + libId + " and I_IsTrue=" + 1, 0, int.MaxValue).Count;
                    if (selLength != answerLenght)
                        isTrue = 0;
                    //在多选时，有一个选项错误，则全错
                    if (isOk == 0)
                        isTrue = 0;
                    testStuAnswerOptionsDAO.Insert(tempOption);//当前学生每个小题选择的答案详情
                }
                //在testStuAnswerDetailz中插入数据
                TbTestStuAnswerDetail tempDetail = new TbTestStuAnswerDetail();
                tempDetail.IStuId = id;
                tempDetail.SStuCode = code;
                tempDetail.IPaperDetailId = DetailId;
                tempDetail.IIsTrue = isTrue;
                tempDetail.IStrategyId = StrategyId;
                tempDetail.IScore = (isTrue == 0 ? 0 : testLibPaperDetailDAO.GetByID(DetailId).IScore);
                testStuAnswerDetailDAO.Insert(tempDetail);//当前学生每个小题详情
            }
            if (NextLibId == 0)//点击提交时，下一题的ID设为0；
                return Json(null);
            return SearchTopic(NextLibId, PaperId);
        }

        /// <summary>
        /// 提交答卷
        /// </summary>
        public int Complete(string Answer, int PaperId, int DetailId = 0, int LibId = 0, int StrategyId = 0)
        {
            int id = frontCurrentStu.GetUserID();//当前学生的ID
            
            string code = frontCurrentStu.GetNo();
            int score = 0;
            NextTopic(0, Answer,PaperId, DetailId, LibId, StrategyId);//提交当前题目答案
            //查找当前试卷有的大题
            IList<TbTestPaperStrategy> strategyList = testPaperStrategyDAO.findByIPaperId(PaperId);
            foreach (var item in strategyList)
            {
                int strategyId = item.Id;
                score = 0;
                TbTestStuAnswer tempStuAnswer = new TbTestStuAnswer();
                //查找当前学生该大题下的所有小题
                TList<TbTestStuAnswerDetail> tempStuDetailList = testStuAnswerDetailDAO.GetByPage(
                    "I_StuID=" + id + " and I_StrategyID=" + strategyId, 0, int.MaxValue);
                foreach (var itemDetail in tempStuDetailList)
                {
                    score += (int)itemDetail.IScore;//累计小题得分，得到大题总分
                }
                tempStuAnswer.IPaperId = PaperId;
                tempStuAnswer.IScore = score;
                tempStuAnswer.IStrateId = strategyId;
                tempStuAnswer.IStuId = id;
                tempStuAnswer.SStuCode = code;
                testStuAnswerDAO.Insert(tempStuAnswer);//当前学生每道大题详情
            }
            //统计当前试卷总分
            score = 0;
            TbTestLibPaper paper = testLibPaperDAO.GetByID(PaperId);
            TbTestScores tbTestScores = new TbTestScores();
            TList<TbTestStuAnswer> answerList = testStuAnswerDAO.GetByPage(
                "I_StuID=" + id + " and I_PaperID=" + PaperId, 0, int.MaxValue);
            foreach (var item in answerList)
            {
                score += (int)item.IScore;//累计大题得分，得到试卷总分
            }
            ClassValueCopier.Copy(tbTestScores, paper);
            tbTestScores.IPaperId = PaperId;
            tbTestScores.IStuId = id;
            tbTestScores.SStuCode = code;
            tbTestScores.IScore = score;
            tbTestScores.IIsRead = 0;
            //添加学生的班级，添加学生姓名
            TbStudents stuInfor = studentsDAO.GetByID(id);
            tbTestScores.SClassCode = stuInfor.SClassCode;
            tbTestScores.SClassName = stuInfor.SClassName;
            tbTestScores.SStuName = stuInfor.SName;
            //课程名
            tbTestScores.SCourseName = new DeanCourseDAO().GetByID((int)tbTestScores.ICourseId).SCourseName;

            new TestScoresDAO().Insert(tbTestScores);//得到当前学生考试总信息
            //更新学生考试表，完成
            TList<TbTestStudents> stuList = testStudentsDAO.GetByPage("I_StuID=" + id + " and I_PaperID=" + PaperId, 0, int.MaxValue);
            if (stuList.Count > 0)
            {
                TbTestStudents stu = stuList[0];
                stu.ICompleted = 1;
                Session["TestCourseID"] = -1;//考试状态，变为没有考试
                testStudentsDAO.Update(stu);
            }
            TbTestScores testScores = new TestScoresDAO().GetByPage(
                "I_StuID=" + id + " and I_PaperID=" + PaperId, 0, int.MaxValue)[0];
            score = (int)testScores.IScore;
            if (score == 0)
                score = -1;
            return score;
        }
    }
}
